package com.wstuo.common.jaas.action;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import java.util.Random;
import java.util.Set;
import javax.security.auth.kerberos.KerberosPrincipal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.jaas.AuthorityGranter;
import org.springframework.transaction.annotation.Transactional;

import com.sun.security.auth.UserPrincipal;
import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.security.dao.IRoleDAO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.dto.LDAPAuthenticationSettingDTO;
import com.wstuo.common.security.dto.LDAPDTO;
import com.wstuo.common.security.dto.UserDTO;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.Role;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.service.ILDAPAuthenticationSettingService;
import com.wstuo.common.security.service.ILDAPService;
import com.wstuo.common.security.service.IRoleService;
import com.wstuo.common.security.service.IUserInfoService;
import com.wstuo.common.util.StringUtils;

/**
 * Security 验证授权
 * 
 * @author Administrator
 * 
 */
public class AuthorityGranterImpl implements AuthorityGranter {
	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private IRoleDAO roleDAO;
	@Autowired
	private IOrganizationDAO organizationDAO;
	@Autowired
	private ILDAPService ldapService;
	@Autowired
	private ILDAPAuthenticationSettingService ldapAuthenticationSettingService;
	@Autowired
	private IUserInfoService userInfoService;

	/**
	 * 角色授权
	 * 
	 * @param principal
	 * @return all role
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public Set grant(Principal principal) {
		Set rtnSet = new HashSet();
		String loginName = "";
		if(principal instanceof UserPrincipal){
			loginName = principal.getName();
			this.useradd(loginName);
		}else if(principal instanceof KerberosPrincipal){
			loginName = principal.getName();
			if (loginName.contains("@")){
				loginName = loginName.substring(0, loginName.lastIndexOf("@"));
				String password = this.getrannumber();
				userInfoService.userKerberos(loginName, password);
			}
		}
		// else if(principal instanceof LdapPrincipal){
		// loginName=principal.getName();
		// if(loginName.contains(",") && loginName.contains("=")){
		// loginName=loginName.split(",")[0].split("=")[1];
		// this.useradd(loginName);
		// }
		// }
		if (StringUtils.hasText(loginName)) {
			User user = userDAO.findUniqueBy("loginName", loginName);
			for (Role role : user.getRoles()) {
				if (role.getRoleState()) {
					rtnSet.add(role.getRoleCode()); // 用户角色
				}
			}
		}
		if (rtnSet.size() == 0) {
			rtnSet.add("ROLE_ENDUSER"); // 终端
		}
		return rtnSet;
	}

	/**
	 * 根据登录名进行添加或更新
	 * 
	 * @param loginName
	 */
	@Transactional
	private void useradd(String loginName) {
		// TODO Auto-generated method stub
		// 根据查找出来的实体为系统插入一个新用户
		String password = this.getrannumber();
		User u = userDAO.findUniqueBy("loginName", loginName);
		if (u == null) {
			LDAPDTO ldapDTO = new LDAPDTO();
			LDAPAuthenticationSettingDTO dto = ldapAuthenticationSettingService
					.findLDAPAuthenticationSetting();// 获取LDAP验证配置信息
			ldapDTO.setLdapType(dto.getLdapType());
			ldapDTO.setLdapURL(dto.getLdapServer());
			ldapDTO.setProt(dto.getProt());
			ldapDTO.setSearchBase(dto.getSearchBase());
			ldapDTO.setAdminName(dto.getAdminName());
			ldapDTO.setAdminPassword(dto.getAdminPassword());
			ldapDTO.setSearchFilter("sAMAccountName=" + loginName);
			UserDTO userDTO = ldapService.checkUserNameIsExist(ldapDTO);
			User user = new User();
			user.setLoginName(loginName);
			user.setPassword(password);
			user.setEmail(userDTO.getEmail());
			user.setPhone(userDTO.getPhone());
			user.setMoblie(userDTO.getMoblie());
			user.setUserState(true);
			user.setUserCost((float) 0);
			user.setCompanyNo(1L);
			List<Role> roles = new ArrayList<Role>();
			Role role = roleDAO.findUniqueBy("roleCode",
					IRoleService.ROLE_ENDUSER);
			if (role != null) {
				roles.add(role);
			}
			if (roles != null) {
				Set<Role> set = new HashSet<Role>(roles);
				user.setRoles(set);
			}
			Organization org = organizationDAO.findById(1L);
			user.setOrgnization(org);
			user.setCreateTime(new Date());
			user.setFirstName(userDTO.getFirstName());
			user.setLastName(userDTO.getLastName());
			user.setFullName("");
			user.setDomain(userDTO.getDomain());
			userDAO.save(user);
		}
	}

	/**
	 * 密码生成规则
	 * 
	 * @return 0~9组合密码
	 */
	public String getrannumber() {
		StringBuffer strbufguess = new StringBuffer();
		String strguess = new String();
		int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		Random rannum = new Random();
		int count;
		int i = 0, temp_i = 0;
		for (int j = 10; j > 4; j--) {
			i = 0;
			temp_i = 0;
			count = rannum.nextInt(j);
			while (i <= count) {
				if (nums[temp_i] == -1)
					temp_i++;
				else {
					i++;
					temp_i++;
				}
			}
			strbufguess.append(Integer.toString(nums[temp_i - 1]));
			nums[temp_i - 1] = -1;
		}
		strguess = strbufguess.toString();
		rannum = null;
		strbufguess = null;
		nums = null;
		return strguess;
	}
}